package kp.rpc.spring.boot.stater.bootStrap;

import kp.rpc.proxy.ServiceProxyFactory;
import kp.rpc.spring.boot.stater.annotation.KpRpcReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;


@Slf4j
public class RpcConsumerBootStrap implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        Field[] declaredFields = beanClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            KpRpcReference annotation = declaredField.getAnnotation(KpRpcReference.class);
            if (annotation != null) {
                Class<?> interfaceClass = annotation.interfaceClass();
                if (interfaceClass == void.class) {
                    interfaceClass = declaredField.getType();
                }
                declaredField.setAccessible(true);
                Object proxy = ServiceProxyFactory.getProxy(interfaceClass);
                try {
                    declaredField.set(bean, proxy);
                    declaredField.setAccessible(false);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
